import type { UseFetchOptions } from '#app';
import type { FetchResponse } from 'ofetch';
import EventBus from "@/utils/eventBus.js";

export interface Response<T> {
  data?: T
  code?: number
  message?: string
  success?: boolean
}
export type HttpOption<T> = UseFetchOptions<Response<T>>;

const handleError = <T>(response: FetchResponse<Response<T>> & FetchResponse<ResponseType>) => {
  const err = (text: string) => {
    // Message.error({
    //   content: response?._data?.message ?? text,
    //   icon: () => h(IconEmoticonDead),
    // })
  }
  if (!response._data) {
    err('请求超时，服务器无响应！')
    return
  }
  // const userStore = useUserStore()
  const handleMap: { [key: number]: () => void } = {
    601: () => {
      err('登录状态已过期，需要重新登录')
      // userStore.clearUserInfo()
      navigateTo('/login')
    },
  }
  handleMap[response.status] ? handleMap[response.status]() : err('未知错误！')
}

const fetch = <T>(url: string, option: UseFetchOptions<Response<T>>) => {
    let resultUrl = url
    // if (process.env.NODE_ENV !== 'development') {
        const runtimeInfo = useRuntimeConfig()
        
        let baseURL = runtimeInfo.public.baseUrl
        
        if (option?.currentBaseUrl) {
            baseURL = runtimeInfo.public[option.currentBaseUrl]
        }
            resultUrl = baseURL + url
    // }
  return useFetch<Response<T>>( resultUrl, {
    // 请求拦截器
    onRequest({ options }) {

        
        // const { public: { baseUrl } } = useRuntimeConfig()
        
        // 根据不同环境请求地址不同
        
        // console.log(baseUrl);
      // 添加请求头,没登录不携带token
      // const userStore = useUserStore()
      // if (!userStore.isLogin) {
      //   return
      // }
      options.headers = new Headers(options.headers)
      if (process.client) {
        let token = localStorage.getItem('aiseo-token-info')
        if (token) {
          options.headers.set('token', token)
        }
      }
    },
    // 响应拦截
    onResponse({ response }) {
    //   // 成功返回
    //   return respons
    try{
      if (response.status === 200) {
        let data = JSON.parse(response._data)
        if(data.code === 601){
          EventBus.emit("openToastBox", [data.message]);
          localStorage.removeItem('aiseo-token-info');
          // 跳转登录页面
          navigateTo('/login')
        }else{
          // EventBus.emit("openToastBox", [data.message]);
        }
        
      }else{
        EventBus.emit("openToastBox", ['请求失败']);
      }
    }catch(e){
      console.log(e);
      
    }
    },
    // 错误处理
    // onResponseError({ response }) {
    //   handleError<T>(response)
    //   return Promise.reject(response?._data ?? null)
    // },
    // 合并参数
    ...option,
  })
}

// 自动导出
export default {
  get: <T>(url: string, params?: any, option?: HttpOption<T>) => {
    return fetch<T>(url, { method: 'get', params, ...option })
  },

  post: <T>(url: string, body?: any, option?: HttpOption<T>) => {
    return fetch<T>(url, { method: 'post', body, ...option })
  },

  put: <T>(url: string, body?: any, option?: HttpOption<T>) => {
    return fetch<T>(url, { method: 'put', body, ...option })
  },

  delete: <T>(url: string, body?: any, option?: HttpOption<T>) => {
    return fetch<T>(url, { method: 'delete', body, ...option })
  },
}
